package com.tendory.gpssim.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.tendory.common.base.RxBus;
import com.tendory.common.per.PermissionsCallbacks;
import com.tendory.common.per.ZPermissions;
import com.tendory.gpssim.Position;
import com.tendory.gpssim.R;
import com.tendory.gpssim.evt.EvtPosSent;
import com.tendory.gpssim.evt.EvtSendSimLoc;
import com.tendory.rxlocation.LocationRequester;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import androidx.core.content.ContextCompat;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = "/map/main")
public class MapActivity extends MapBaseActivity {

    private Handler handler = new Handler();
    private Runnable delayRun = this::delayInitMap;
    private Button simLoc, simSend;

    private final CompositeDisposable disposables = new CompositeDisposable();
    public void addSubscription(Disposable s) {
        disposables.add(s);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        disposables.clear();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.map);
        getWindow().getDecorView().post(() -> handler.postDelayed(delayRun, 0));

        addSubscription(RxBus.getInstance().toObserverable(EvtPosSent.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::onEvtPosSent, Throwable::printStackTrace));

        simLoc = findViewById(R.id.sim_loc);
        simSend = findViewById(R.id.sim_send);
        simLoc.setOnClickListener(v -> showSimLoc());
        simSend.setOnClickListener(v -> showSimSend());
        simSend.setVisibility(View.GONE);
    }

    private void showSimSend() {
        if (simLocMarker == null || curSelLoc == null) {
            Toast.makeText(this, "还没选择位置", Toast.LENGTH_SHORT).show();
            return;
        }
        EventBus.getDefault().post(new EvtSendSimLoc(curSelLoc.latitude, curSelLoc.longitude));
    }

    private Marker simLocMarker;
    private void showSimLoc() {
        if (curLoc == null) {
            Toast.makeText(this, "还没定位", Toast.LENGTH_SHORT).show();
            return;
        }
        if (simLocMarker == null) {
            MarkerOptions markerOptions = new MarkerOptions()
                    .setFlat(true)
                    .anchor(0.5f, 0.95f)
                    .draggable(false);
            simLocMarker = mAMap.addMarker(markerOptions);
            simLocMarker.setTitle("SimLoc");
            simLocMarker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.sim_loc));
            setSimLog(curLoc);
            simLoc.setText("结束模拟定位");
            simSend.setVisibility(View.VISIBLE);
        } else {
            simLocMarker.remove();
            simLocMarker = null;
            curSelLoc = null;
            simLoc.setText("开始模拟定位");
            simSend.setVisibility(View.GONE);
        }
    }

    private LatLng curSelLoc;
    private void setSimLog(LatLng curLoc) {
        simLocMarker.setPosition(curLoc);
        curSelLoc = curLoc;
    }

    private Marker marker;
    private LatLng curLoc;
    private void delayInitMap() {
        initMapDelay();
        initMapView();
        ZPermissions.with(this).permission(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
        )
                .setPermissionsCallbacks(new PermissionsCallbacks() {
                    @Override
                    public void onPermissionsGranted(int requestCode, List<String> perms) {
                        marker = onCreateMarker();
                        addSubscription(new LocationRequester().requestLocation()
                                .take(1)
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(loc -> {
                                    LatLng point = new LatLng(loc.getLatitude(), loc.getLongitude());
                                    float zoom = mAMap.getCameraPosition().zoom;
                                    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(point, zoom);
                                    mAMap.moveCamera(update);
                                    curLoc = point;
                                    setPosition(marker, point, 0);
                                }, throwable -> {}));
                    }

                    @Override
                    public void onPermissionsDenied(int requestCode, List<String> perms) {
                        finish();
                    }
                }).request();
    }

    private void onEvtPosSent(EvtPosSent position) {
        LatLng point = new LatLng(position.getPosition().getLatitude(), position.getPosition().getLongitude());
        curLoc = point;
        setPosition(marker, point, (float) position.getPosition().getCourse());
    }

    private Marker onCreateMarker() {
        MarkerOptions markerOptions = new MarkerOptions()
                .setFlat(true)
                .anchor(0.5f, 0.4f)
                .draggable(false);
        Marker mMoveMarker = mAMap.addMarker(markerOptions);
        mMoveMarker.setTitle("Loc");
        mMoveMarker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.mark));
        return mMoveMarker;
    }

    private void setPosition(Marker marker, LatLng location, float dir) {
        float rotate = (360 - dir + 180) % 360;
        marker.setRotateAngle(rotate);
        marker.setPosition(location);
//        marker.setSnippet(formatDetails(this, position.getSpeed()));
    }

    private void initMapView() {
        setMapStyle();
        setMyLocStyle();
        mAMap.setOnMapClickListener(this::setSimLog);
    }

}
